<?php 
/*
 *  This file is part of Urd.
 *
 *  Urd is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *  Urd is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program. See the file "COPYING". If it does not
 *  exist, see <http://www.gnu.org/licenses/>.
 *
 * $LastChangedDate: 2008-07-10 23:59:20 +0200 (Thu, 10 Jul 2008) $
 * $Rev: 1285 $
 * $Author: gavinspearhead $
 * $Id: ajax_showstatus.php 1285 2008-07-10 21:59:20Z gavinspearhead $
 */
define('ORIGINAL_PAGE', $_SERVER['PHP_SELF']);
$__auth = 'silent';

$pathajss = realpath(dirname(__FILE__));

require_once "$pathajss/../functions/ajax_includes.php"; 

$STATUS = '';

$root_prefs = load_config($db);

$versionchecking = $status_newversion = $status_bugfix = $status_newfeature = $status_other = $status_security = 0;
$newversionnumber = '?';

// First: Basic stats.
// can we connect?
$uc = new urdd_client($root_prefs['urdd_host'], $root_prefs['urdd_port'], $userID);
$isconnected = $uc->is_connected();

// Status of updates:
// Only show version update info if version checking is scheduled:

$tasks = array(); 
$diskspace = array(0=>'', 1=>'');
$disk_perc = $nodisk_perc = 0;

if ($root_prefs['period_update'] > 0) {
	$versionchecking = 1;
	// New version info:
	$newversionnumber = $root_prefs['update_version'];
	$type = $root_prefs['update_type'] ;
	$type_msg = '';
	if ($type !== UPDATE_NO_UPDATE && version_compare($newversionnumber, get_version(), '>')) {  // There is a version available AND it's a higher version number
		if (($type & UPDATE_NEW_VERSION) != 0)	$status_newversion = 1;
		if (($type & UPDATE_BUG_FIX) != 0)	$status_bugfix = 1;
		if (($type & UPDATE_NEW_FEATURE) != 0) 	$status_newfeature = 1;
		if (($type & UPDATE_OTHER) != 0)	$status_other = 1;
		if (($type & UPDATE_SECURITY_FIX) != 0)	$status_security = 1;
	}	 
}	

$startup_perc = get_config($db, 'urdd_startup');
$cnt = 0;

if ($isconnected) {
	// Second: Current jobs.
	$sql = '"description", max("progress") AS "progress", min("ETA") as "ETA", min("command_id") AS "command_id", count("ID") as "counter" FROM queueinfo WHERE "status" = \''. QUEUE_RUNNING .'\' GROUP BY "description"';// ORDER BY "ID" DESC';
    $res = $db->select_query($sql, 10); // why only 10?
	if ($res === FALSE) 
		$res = array();
	// Check the number of jobs we display:
//	$count = 0; // not used?

    $tasks = array();

	foreach ($res as $row) {
		$task = $row['description'];
		$progress = $row['progress'] = min(100, $row['progress']);
		$ETA = $row['ETA'];
        $command_id = $row['command_id'];
      //  $count = $row['counter'];

		// We're gonna use $row as the array containing all data:
		$row['niceeta'] = -1;
		$row['target'] = '';
		$isUpdate = $isUpdateRSS = $isCheckVersion = $isPurge = $isPurgeRSS = $isExpireRSS = $isExpire = $isDeleteSet = 
		$isDownload = $isDownload = $isGroups = $isOptimise = $isUnParRar = $isGetSetInfo = $isSendSetInfo = $isPost =
		$isGenSets = $isAddData = $isParseNZB = $isMakeNZB = $isCleanDir = $isCleanDb = $isMergeSets = $isFindServers = FALSE;
	//	$count++; // never used ?
        switch($command_id) {
        case COMMAND_DELETE_SET:
        case COMMAND_DELETE_SET_RSS:
            $isDeleteSet = TRUE;
            $row['name'] = $LN['cmd_descr_deleteset'];
            $row['type'] = 'update'; //XXX
            break;
        case COMMAND_FINDSERVERS:
            $isFindServers = TRUE;
            $row['name'] = $LN['taskfindservers'];
            $row['type'] = 'findservers';
            break;
		case COMMAND_UPDATE:
			$groupID = str_ireplace(get_command(COMMAND_UPDATE) . ' ', '', $task);
			$row['name'] = $LN['taskupdate'];		
			$row['type'] = 'update';
			$isUpdate = TRUE;
            break;
		case COMMAND_UPDATE_RSS: 
			$feedID = str_ireplace(get_command(COMMAND_UPDATE_RSS) . ' ', '', $task);
			$row['name'] = $LN['taskupdate'];	
			$row['type'] = 'update';
			$isUpdateRSS = TRUE; 
			break;
		case COMMAND_CHECK_VERSION: 
			$row['name'] = $LN['taskcheckversion'];	
			$row['type'] = 'checkversion';
			$isCheckVersion = TRUE;
            break;
		case COMMAND_PURGE:
			$groupID = str_ireplace(get_command(COMMAND_PURGE) . ' ', '', $task);
			$row['name'] = $LN['taskpurge'];
			$row['type'] = 'purge';
			$isPurge = TRUE;
            break;
		case COMMAND_PURGE_RSS:
			$feedID = str_ireplace(get_command(COMMAND_PURGE_RSS). ' ', '', $task);
			$row['name'] = $LN['taskpurge'];
			$row['type'] = 'purge';
			$isPurgeRSS = TRUE; 
			break;
		case COMMAND_EXPIRE_RSS: 
			$feedID = str_ireplace(get_command(COMMAND_EXPIRE_RSS). ' ', '', $task);
			$row['name'] = $LN['taskexpire'];	
			$row['type'] = 'expire';
			$isExpireRSS = TRUE; 
			break;
		case COMMAND_EXPIRE:
			$groupID = str_ireplace(get_command(COMMAND_EXPIRE) . ' ', '', $task);
			$row['name'] = $LN['taskexpire'];	
			$row['type'] = 'expire';
			$isExpire =TRUE; 
			break;
		case COMMAND_DOWNLOAD: // just an alias, but internally differently handled
		case COMMAND_DOWNLOAD_ACTION : 
			$ID = str_ireplace(get_command(COMMAND_DOWNLOAD) . ' ', '', $task);
			$ID = str_ireplace(get_command(COMMAND_DOWNLOAD_ACTION) . ' ', '', $task);
			$row['name'] = $LN['taskdownload'];	
			$row['type'] = 'download';
			$isDownload = TRUE;
            break;
        case COMMAND_GROUPS:
            $row['name'] = $LN['taskgrouplist'];	
            $row['type'] = 'grouplist';
            $isGroups = TRUE; 
            break;
        case COMMAND_OPTIMISE: 
            $row['name'] = $LN['taskoptimise'];	
            $row['type'] = 'optimise';
            $isOptimise = TRUE; 
            break;
        case COMMAND_UNPAR_UNRAR:
            $row['name'] = $LN['taskunparunrar'];	
            $row['type'] = 'unparunrar';
            $isUnParRar = TRUE;
            break;
        case COMMAND_GETSETINFO:
            $row['name'] = $LN['taskgetsetinfo'];	
            $row['type'] = 'getsetinfo';
            $isGetSetInfo = TRUE;
            break;
        case COMMAND_SENDSETINFO:
            $row['name'] = $LN['tasksendsetinfo'];	
            $row['type'] = 'sendsetinfo';
            $isSendSetInfo = TRUE;
            break;
        case COMMAND_GENSETS:
            $groupID = str_ireplace(get_command(COMMAND_GENSETS). ' ', '', $task);
            $row['name'] = $LN['taskgensets'];
            $row['type'] = 'update';
            $isGenSets = TRUE;
            break;
        case COMMAND_ADDDATA: 
            $isAddData = TRUE; 
            $row['name'] = $LN['taskadddata'];
            $row['type'] = 'adddata';
            break;
        case COMMAND_PARSE_NZB:
            $row['name'] = $LN['taskparsenzb'];
            $row['type'] = 'parsenzb';
            $isParseNZB = TRUE;
            break;
        case COMMAND_MAKE_NZB: 
            $row['name'] = $LN['taskmakenzb'];
            $row['type'] = 'makenzb';
            $isMakeNZB = TRUE; 
            break;
        case COMMAND_CLEANDIR: 
            $row['name'] = $LN['taskcleandir'];		
            $row['type'] = 'cleandir';
            $isCleanDir = TRUE;
            break;
        case COMMAND_CLEANDB: 
            $row['name'] = $LN['taskcleandb'];		
            $row['type'] = 'cleandb';
            $isCleanDb = TRUE;
            break;
        case COMMAND_MERGE_SETS:
            $row['name'] = $LN['taskmergesets'];		
            $row['type'] = 'mergesets';
            $isMergeSets = TRUE;
            break;
        case COMMAND_POST:
        case COMMAND_START_POST:
        case COMMAND_POST_ACTION:
            $row['name'] = $LN['taskpost'];	
            $row['type'] = 'post';
            $ID = str_ireplace(get_command(COMMAND_POST_ACTION) . ' ', '', $task); 
            $ID = str_ireplace(get_command(COMMAND_START_POST) . ' ', '', $ID); 
            $ID = str_ireplace(get_command(COMMAND_POST) . ' ', '', $ID); 
            $isPost = TRUE;
            break;
        default :
            continue 2 ; // needs 2 coz php considers switch a loop too :-(
            break;
        }

        // For tasks that end with a groupID:
        if ($isPurge || $isUpdate || $isExpire || $isGenSets) {
            $name = group_name($db, $groupID);
            $row['target'] = shorten_newsgroup_name ($name, 0);
        } elseif ($isPurgeRSS || $isUpdateRSS || $isExpireRSS) {
            $name = feed_name($db, $feedID);
            $row['target'] = shorten_newsgroup_name($name, 0);
        } elseif ($isDownload) {
            $name = get_download_name($db, $ID);
            $row['target'] = $name;
        } elseif ($isUnParRar) {
            $tmp = explode(' ', $task);
            $ID = $tmp[count($tmp)-1];
            try {
                $name = get_download_name($db, $ID);
                $row['target'] = $name;
            } catch (exception $e) {
                continue;
            }
        } elseif ($isAddData) {
            $tmp = explode(' ', $task);
            $ID = $tmp[1];
            try {
                $name = get_download_name($db, $ID);
                $row['target'] = $name;
            } catch (exception $e) {
                continue;
            }
        } elseif ($isPost) {
            try {
                $row['target'] =  get_post_name($db, $ID);
            } catch (exception $e) {
                continue;
            }
        }

        if ($isUpdate || $isOptimise || $isExpire || $isCheckVersion || $isSendSetInfo || $isGetSetInfo || $isPost || $isGenSets
            || $isDownload|| $isParseNZB || $isCleanDir || $isUpdateRSS || $isExpireRSS || $isPurgeRSS || $isCleanDb || $isMergeSets) 
            if ($progress < 100 && $ETA != 0) 
                $row['niceeta'] = readable_time($ETA, 'fancy');

        // Uniquify:
        $arrayid = $row['target'] . $row['name'];

		// $tasks are previously added items, $row is current item.
		// If there's a previous item, it might be merged with this one if they are identical.

		// Create or Overwrite the item:
		$tasks[$arrayid] = $row;
	}
    $cnt = count($tasks);
	$diskspace = $uc->diskfree('h');
	$disk_perc = $uc->diskfree('p1');
	$nodisk_perc = 100 - (int) $disk_perc;
	$uc->disconnect();
}


// Filter id's:
$cleartasks = array();
foreach ($tasks as $key => $task)
	$cleartasks[] = $task;

$challenge = set_challenge();

$taskmax1 = $prefs['taskmax1'];
$taskmax2 = $prefs['taskmax2'];

$smarty->assign('challenge',        $challenge);
$smarty->assign('newversionnumber',	$newversionnumber);
$smarty->assign('status_newversion',	$status_newversion);
$smarty->assign('status_bugfix',	$status_bugfix);
$smarty->assign('status_newfeature',	$status_newfeature);
$smarty->assign('status_other',		$status_other);
$smarty->assign('status_security',	$status_security);
$smarty->assign('startup_perc',	    $startup_perc);
$smarty->assign('tasks',		    $cleartasks);
$smarty->assign('diskfree',		    $diskspace[0] . ' ' .$diskspace[1]);
$smarty->assign('disk_perc',		$disk_perc);
$smarty->assign('nodisk_perc',		$nodisk_perc);
$smarty->assign('URDDOWNLOADURL',	DOWNLOAD_URL);
$smarty->assign('URD_VERSION',		get_version());
$smarty->assign('isadmin',	    	$isadmin);
$smarty->assign('counter',	    	$cnt);
$smarty->assign('taskmax1',	    	$taskmax1);
$smarty->assign('taskmax2',	    	$taskmax2);
$smarty->assign('isconnected',		$isconnected);
$smarty->assign('versionchecking',	$versionchecking);
$smarty->display('ajax_showstatus.tpl');

?>
